package com.whir.rd.swd;

import com.whir.common.db.Dbutil;
import com.whir.component.security.crypto.EncryptUtil;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.binary.Base64;

public class SendFlow2QMS
{
  private Map<String, String> proMap = urlMap();
  private String synchronousTransfer = (String)this.proMap.get("synchronousTransfer");
  private String fileUploadUrl = (String)this.proMap.get("fileUploadUrl");
  private String idmURLSSOLogin = (String)this.proMap.get("idmURLSSOLogin");

  public static Map<String, String> urlMap()
  {
    Map map = new HashMap();
    Properties prop = new Properties();
    InputStream in = SendFlow2QMS.class.getResourceAsStream("pushTask.properties");
    try
    {
      prop.load(in);
      Set set = prop.keySet();
      for (Iterator localIterator = set.iterator(); localIterator.hasNext(); ) {
        Object obj = localIterator.next();
//        map.put(obj.toString(), prop.getProperty(obj));
      }
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }

    return map;
  }

  public void pushStatus(String status, HttpServletRequest request)
  {
    System.out.println("=======SendFlowStatusToDoc-start=======");

    String url = this.synchronousTransfer;

    Map data = getFlowData(request.getParameter("infoId"));
    checkData(data, status, request);
    String soapXml = createSOAPXml(data);
    sendHttp(url, soapXml);
    System.out.println("=======SendFlowStatusToDoc-end=======");
  }

  public Map<String, Object> getFlowData(String infoId)
  {
    Map data = new HashMap();
    Dbutil dbutil = new Dbutil();
    String sql = "select whir$t3202_f5958,whir$t3202_f5959,whir$t3202_f5960,whir$t3202_f5961,whir$t3202_f5962,whir$t3202_f5963,whir$t3202_f5964,whir$t3202_f6248,whir$t3202_f6249,whir$t3202_f5965,whir$t3202_f5999,whir$t3202_f5966,whir$t3202_f5967,whir$t3202_f13059,whir$t3202_dataFrom,whir$t3202_date,whir$t3202_f22763 from whir$t3202 where whir$t3202_id = :infoId";

    data.put("infoId", infoId);
    try {
      Object[] o = dbutil.getFirstDataBySQL(sql, data);
      if ((o != null) && (o.length > 0)) {
        data.put("billno", o[0]);
        data.put("sponsorUnit", o[1]);
        data.put("dutyUnit", o[2]);
        data.put("materialNo", o[3]);
        data.put("name", o[4]);
        data.put("processNo", o[5]);
        data.put("deliveriesNum", o[6]);
        data.put("checkNum", o[7]);
        data.put("noNum", o[8]);
        data.put("rmark", o[9]);
        data.put("realAcc", getFileUrl(o[10].toString()));
        data.put("level", o[11]);
        data.put("checkUserAccount", o[12]);
        data.put("endStatus", o[13]);
        System.out.println("==========================dataSource=" + o[14]);
        data.put("dataSource", (o[14] == null) || ("".equals(o[14])) ? "OA" : o[14]);
        data.put("createData", o[15].toString());
        data.put("fbk2", o[16] == null ? "" : o[16].toString());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return data;
  }

  public String getFileUrl(String data)
  {
    System.out.println("=================================getFileUrl data=" + data);
    String fileUrl = "";
    if (!"".equals(data)) {
      String fileNameStr = data.split(";")[1];
      String saveNameStr = data.split(";")[0];
      String[] fileNames = fileNameStr.split(",");
      String[] saveNames = saveNameStr.split(",");
      for (int i = 0; i < saveNames.length; i++) {
        String saveName = saveNames[i];
        if ((saveName != null) && (!"".equals(saveName))) {
          String separator = saveName.substring(0, 6);
          String uploadUrl = this.fileUploadUrl + "/defaultroot/upload/customform/" + separator + File.separator + saveName;
          fileUrl = fileUrl + fileNames[i] + "|" + uploadUrl + ";";
        }
      }
      fileUrl = fileUrl.substring(0, fileUrl.length() - 1);
      System.out.println("=================================getFileUrl fileUrl=" + fileUrl);
    }
    return fileUrl;
  }

  public void checkData(Map<String, Object> data, String status, HttpServletRequest request)
  {
    if ("0".equals(status)) {
      data.put("status", "办理完成");
      String p_wf_processInstanceId = request.getParameter("p_wf_processInstanceId");
      EncryptUtil util = new EncryptUtil();
      String encode = util.getSysEncoderKeyVlaue("p_wf_processInstanceId", p_wf_processInstanceId, "WFDealWithAction");

      String ssoUrl = this.idmURLSSOLogin;

      String url = "/defaultroot/ezflowopen!updateProcess.action?p_wf_openType=modifyView&p_wf_processInstanceId=" + p_wf_processInstanceId + "&verifyCode=" + encode;
      try {
        ssoUrl = ssoUrl + new String(Base64.encodeBase64(url.getBytes("UTF-8")));
        data.put("resume", ssoUrl);
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
    } else if ("1".equals(status)) {
      data.put("status", "退回");

      String p_wf_processInstanceId = request.getParameter("p_wf_processInstanceId");
      EncryptUtil util = new EncryptUtil();
      String encode = util.getSysEncoderKeyVlaue("p_wf_processInstanceId", p_wf_processInstanceId, "WFDealWithAction");

      String ssoUrl = this.idmURLSSOLogin;

      String url = "/defaultroot/ezflowopen!updateProcess.action?p_wf_openType=myTask&p_wf_processInstanceId=" + p_wf_processInstanceId + "&verifyCode=" + encode;
      try {
        ssoUrl = ssoUrl + new String(Base64.encodeBase64(url.getBytes("UTF-8")));
        data.put("resume", ssoUrl);
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
    } else if ("2".equals(status)) {
      data.put("status", "取消");
    }
  }

  public String createSOAPXml(Map<String, Object> data)
  {
    String soap = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:rnp=\"http://rnpreview.webservice.bjf.com/\"><soapenv:Header/><soapenv:Body><rnp:receiveData><arg0><attachment>" + 
      data.get("realAcc") + "</attachment>" + 
      "<billno>" + data.get("billno") + "</billno>" + 
      "<checkNum>" + data.get("checkNum") + "</checkNum>" + 
      "<dataSource>" + data.get("dataSource") + "</dataSource>" + 
      "<deliveriesNum>" + data.get("deliveriesNum") + "</deliveriesNum>" + 
      "<describeItem>" + data.get("level") + "</describeItem>" + 
      "<dutyUnit>" + data.get("dutyUnit") + "</dutyUnit>" + 
      "<examinationClerk>" + data.get("checkUserAccount") + "</examinationClerk>" + 
      "<fbk1>" + data.get("createData") + "</fbk1>" + 
      "<fbk2>" + data.get("fbk2") + "</fbk2>" + 
      "<fbk10></fbk10>" + 
      "<fbk3></fbk3>" + 
      "<fbk4></fbk4>" + 
      "<fbk5></fbk5>" + 
      "<fbk6></fbk6>" + 
      "<fbk7></fbk7>" + 
      "<fbk8></fbk8>" + 
      "<fbk9></fbk9>" + 
      "<materialName>" + data.get("name") + "</materialName>" + 
      "<materialNo>" + data.get("materialNo") + "</materialNo>" + 
      "<nonCheckDescription>" + data.get("rmark") + "</nonCheckDescription>" + 
      "<processNoAndRedHandleNum>" + data.get("processNo") + "</processNoAndRedHandleNum>" + 
      "<resume>" + data.get("resume") + "</resume>" + 
      "<reviewConclusion>" + data.get("endStatus") + "</reviewConclusion>" + 
      "<sponsorUnit>" + data.get("sponsorUnit") + "</sponsorUnit>" + 
      "<status>" + data.get("status") + "</status>" + 
      "<technician></technician>" + 
      "<unqualifiedNum>" + data.get("noNum") + "</unqualifiedNum>" + 
      "</arg0>" + 
      "</rnp:receiveData>" + 
      "</soapenv:Body>" + 
      "</soapenv:Envelope>";
    System.out.println("soapXml=" + soap);
    return soap;
  }

  public String sendHttp(String url, String soapXml)
  {
    System.out.println("usl:" + url);
    String result = "";
    URL wsUrl = null;
    OutputStream os = null;
    InputStream is = null;
    HttpURLConnection conn = null;
    try {
      wsUrl = new URL(url);
      conn = (HttpURLConnection)wsUrl.openConnection();
      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
      os = conn.getOutputStream();
      os.write(soapXml.getBytes("utf-8"));

      is = conn.getInputStream();
      byte[] b = new byte[1024];
      int len = 0;
      while ((len = is.read(b)) != -1) {
        String ss = new String(b, 0, len, "UTF-8");
        result = result + ss;
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
    catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        is.close();
      }
      catch (IOException e1) {
        e1.printStackTrace();
      }
      try {
        os.close();
      }
      catch (IOException e) {
        e.printStackTrace();
      }
      conn.disconnect();
    }
    System.out.println("webserviceResult=" + result);
    return result;
  }
}